package model

import (
	"context"
	"fmt"

	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ InboxMessageModel = (*customInboxMessageModel)(nil)

type (
	// InboxMessageModel is an interface to be customized, add more methods here,
	// and implement the added methods in customInboxMessageModel.
	InboxMessageModel interface {
		inboxMessageModel
		RowBuilder() squirrel.SelectBuilder
		Truncate(ctx context.Context)
		FindAll(ctx context.Context) ([]*InboxMessage, error)
		MessagePagation(ctx context.Context, userId int64, offset int64, limit int64, asc bool, includer_read bool) ([]*InboxMessage, error)
	}

	customInboxMessageModel struct {
		*defaultInboxMessageModel
	}
)

// NewInboxMessageModel returns a model for the database table.
func NewInboxMessageModel(conn sqlx.SqlConn, c cache.CacheConf) InboxMessageModel {
	return &customInboxMessageModel{
		defaultInboxMessageModel: newInboxMessageModel(conn, c),
	}
}

func (m *defaultInboxMessageModel) RowBuilder() squirrel.SelectBuilder {
	return squirrel.Select(inboxMessageRows).From(m.table)
}

func (m defaultInboxMessageModel) Truncate(ctx context.Context) {
	build := m.RowBuilder()
	query, values, err := build.ToSql()
	if err == nil {
		var resp []*InboxMessage
		err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
		if err == nil {
			for _, r := range resp {
				m.Delete(ctx, r.Id)
			}
			m.ExecNoCacheCtx(ctx, fmt.Sprintf("TRUNCATE %s", m.tableName()))
		}
	}
}

func (m defaultInboxMessageModel) FindAll(ctx context.Context) ([]*InboxMessage, error) {
	build := m.RowBuilder()
	query, values, err := build.ToSql()
	if err != nil {
		return nil, nil
	}

	var resp []*InboxMessage
	err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return nil, err
	}
}

func (m defaultInboxMessageModel) MessagePagation(ctx context.Context, userId int64, offset int64, limit int64, asc bool, includer_read bool) ([]*InboxMessage, error) {
	build := m.RowBuilder()
	order_dir := "desc"
	if asc {
		order_dir = "asc"
	}
	query, values, err := build.Where("sender=? or receiver=? ",
		userId, userId).OrderBy(" id " + order_dir).Offset(uint64(offset)).Limit(uint64(limit)).ToSql()
	if err == nil {
		var resp []*InboxMessage
		err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
		if err == nil {
			return resp, nil
		}
		return nil, err
	}
	logx.Infof("================== error:%v", err)
	return nil, err
}
